<!-- src/views/video/task/index.vue -->
<template>
  <div class="task-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="文章标题" prop="title" style="width: 300px" >
          <el-input v-model="queryParams.title" placeholder="请输入文章标题" clearable />
        </el-form-item>
        <el-form-item label="分类">
          <el-cascader
              v-model="queryParams.categoryId"
              :options="categoryOptions"
              :props="{
          checkStrictly: true,
          label: 'name',
          value: 'id',
          emitPath: false
        }"
              placeholder="选择分类"
              clearable
              style="width: 240px;"
          >
            <template #default="{ node, data }">
              <span>{{ data.name }}</span>
              <span v-if="!node.isLeaf"> ({{ data.children?.length || 0 }}) </span>
            </template>
          </el-cascader>
        </el-form-item>
        <el-form-item label="任务状态" prop="status" style="width: 200px" >
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围" prop="timeRange">
          <el-date-picker
              v-model="queryParams.timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 任务列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <div class="left">
            <el-button type="danger" :disabled="!selectedTasks.length" @click="handleBatchDelete">
              批量删除
            </el-button>
            <el-button type="primary" :disabled="!selectedTasks.length" @click="handleBatchRetry">
              批量重试视频
            </el-button>
            <el-button type="success" :disabled="!selectedTasks.length" @click="handleBatchDownload">
              批量下载视频
            </el-button>
            <el-tag v-if="selectedTasks.length" type="info">
              已选择 {{ selectedTasks.length }} 项
            </el-tag>
          </div>
          <div class="right">
            <el-space>
              <el-tag>当前页面统计</el-tag>
              <el-tag type="info">总任务: {{ total }}</el-tag>
              <el-tag type="warning">生成中: {{ generatingCount }}</el-tag>
              <el-tag type="success">已完成: {{ completedCount }}</el-tag>
              <el-tag type="danger">失败: {{ failedCount }}</el-tag>
            </el-space>
          </div>
        </div>
      </template>

      <!-- 任务列表表格 -->
      <el-table v-loading="loading"
                :data="taskList"
                @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="expand">
          <template #default="props">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="文章内容">
                {{ props.row.description }}
              </el-descriptions-item>
              <el-descriptions-item label="回调ID">
                {{ props.row.callbackId }}
              </el-descriptions-item>
              <el-descriptions-item label="错误信息" v-if="props.row.errorMessage" width="100">
                <el-tag type="danger">{{ props.row.errorMessage }}</el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </template>
        </el-table-column>
        <el-table-column label="GIF预览" prop="gif" width="200" >
          <template #default="props">
            <!-- 添加 GIF 预览 -->
            <img v-if="props.row.gifUrl" :src="props.row.gifUrl" class="preview-gif"  :alt=props.row.title width="200"/>
          </template>
        </el-table-column>
        <el-table-column label="文章标题" prop="title" :show-overflow-tooltip="true" />
<!--        <el-table-column label="分类" prop="categoryName" :show-overflow-tooltip="true" />-->
        <el-table-column label="分类" prop="categoryName" :show-overflow-tooltip="true">
          <template #default="{ row }">
            <span>{{ row.categoryPath || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="任务状态" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="错误信息" prop="errorMessage" width="240" >
          <template #default="scope">
            <el-tag type="danger" v-if="scope.row.errorMessage">
              {{ scope.row.errorMessage }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="240" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button-group>
              <el-tooltip content="预览" placement="top">
                <el-button link type="primary" :icon="View"
                           @click="handlePreview(scope.row)"
                           v-if="scope.row.videoUrl"
                />
              </el-tooltip>
              <el-tooltip content="下载" placement="top">
                <el-button link type="primary" :icon="Download"
                           @click="handleDownload(scope.row)"
                           v-if="scope.row.videoUrl"
                />
              </el-tooltip>
              <el-tooltip content="重试" placement="top">
                <el-button link type="warning" :icon="RefreshRight"
                           @click="handleRetry(scope.row)"
                           v-if="scope.row.status === '生成失败'"
                />
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="danger" :icon="Delete"
                           @click="handleDelete(scope.row)"
                />
              </el-tooltip>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 视频预览弹窗 -->
    <el-dialog
        v-model="previewDialog.visible"
        :title="previewDialog.title"
        width="800px"
        :close-on-click-modal="false"
    >
      <video
          v-if="previewDialog.videoUrl"
          :src="previewDialog.videoUrl"
          controls
          class="preview-video"
      ></video>
      <template #footer>
        <el-button @click="handleDownload(previewDialog.task)" type="primary">
          <el-icon><Download /></el-icon>下载视频
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Download, RefreshRight, View, VideoCamera, Delete, Refresh} from '@element-plus/icons-vue'
import { useTaskStore } from '@/stores/task'
import {batchDeleteTasks, batchRetryTask, deleteTask, downloadVideos, retryTask} from "@/api/task.js";
import {getCategoryTree} from "@/api/category.js";

const taskStore = useTaskStore()

// 选中的任务
const selectedTasks = ref([])

// 计算属性
const hasCompletedTasks = computed(() =>
    selectedTasks.value.some(task => task.status === '生成完成')
)

const hasFailedTasks = computed(() =>
    selectedTasks.value.some(task => task.status === '生成失败')
)

const generatingCount = computed(() =>
    taskList.value.filter(task => task.status === '生成中').length
)

const completedCount = computed(() =>
    taskList.value.filter(task => task.status === '生成完成').length
)

const failedCount = computed(() =>
    taskList.value.filter(task => task.status === '生成失败').length
)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: '',
  status: '',
  category: '',
  categoryId: '',
  timeRange: []
})

// 状态选项
const statusOptions = [
  { value: 0, label: '待生成' },
  { value: 1, label: '生成中' },
  { value: 2, label: '生成完成' },
  { value: 3, label: '生成失败' }
]

// 表格数据
const loading = ref(false)
const taskList = ref([])
const total = ref(0)

// 预览弹窗
const previewDialog = reactive({
  visible: false,
  videoUrl: ''
})

// 定时刷新任务
let refreshTimer = null

// 删除单个任务
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该任务吗？', '提示', {
      type: 'warning'
    })
    await deleteTask(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 批量下载
const handleBatchDownload = async () => {
  try {
    const completedTasks = selectedTasks.value.filter(task => task.status === '生成完成')
    if (!completedTasks.length) {
      ElMessage.warning('请选择已完成的任务')
      return
    }

    loading.value = true
    // 指定响应类型为blob
    const response = await downloadVideos(completedTasks.map(t => t.id), {
      responseType: 'blob'
    })

    // 检查响应类型
    if (!response.data || !(response.data instanceof Blob)) {
      throw new Error('下载响应格式错误')
    }

    const url = window.URL.createObjectURL(response.data)
    const link = document.createElement('a')
    link.href = url
    // 获取文件名,添加错误处理
    const contentDisposition = response.headers['content-disposition']
    const fileName = contentDisposition ?
        contentDisposition.split('filename=')[1] :
        `videos_${new Date().getTime()}.zip`

    link.download = fileName
    document.body.appendChild(link)
    link.click()
    window.URL.revokeObjectURL(url)
    document.body.removeChild(link)

    // 清理
    setTimeout(() => {
      window.URL.revokeObjectURL(url)
      document.body.removeChild(link)
    }, 100)
    ElMessage.success('下载开始')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error(`下载失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
        `确定要删除选中的 ${selectedTasks.value.length} 个任务吗？`,
        '提示',
        { type: 'warning' }
    )
    await batchDeleteTasks(selectedTasks.value.map(t => t.id))
    ElMessage.success('批量删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '批量删除失败')
    }
  }
}

// 批量重试
const handleBatchRetry = async () => {
  const failedTasks = selectedTasks.value.filter(task => task.status === '生成失败')
  if (!failedTasks.length) return

  try {
    await ElMessageBox.confirm(`确定要重试选中的 ${failedTasks.length} 个失败任务吗？`)

    // 提取任务ID
    const taskIds = failedTasks.map(task => task.id)

    // 调用批量重试API
    await batchRetryTask(taskIds)

    ElMessage.success('批量重试任务已提交')
    await getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '批量重试失败')
    }
  }
}

// 表格选择
const handleSelectionChange = (selection) => {
  selectedTasks.value = selection
}

// 获取任务列表
const getList = async () => {
  loading.value = true
  try {
    const params = {
      ...queryParams,
      startTime: queryParams.timeRange?.[0],
      endTime: queryParams.timeRange?.[1],
    }
    // 删除 timeRange 参数
    delete params.timeRange

    await taskStore.fetchTaskList(params)
    taskList.value = taskStore.tasks.records
    total.value = taskStore.tasks.total

    // 检查是否需要继续轮询（有正在生成的任务）
    const hasGeneratingTask = taskList.value.some(task => task.status === '生成中')
    if (hasGeneratingTask && !refreshTimer) {
      startRefreshTimer()
    } else if (!hasGeneratingTask && refreshTimer) {
      stopRefreshTimer()
    }
  } finally {
    loading.value = false
  }
}

// 开始定时刷新
const startRefreshTimer = () => {
  refreshTimer = setInterval(() => {
    getList()
  }, 30000) // 每30秒刷新一次
}

// 停止定时刷新
const stopRefreshTimer = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置
const resetQuery = () => {
  queryParams.title = ''
  queryParams.status = ''
  queryParams.timeRange = []
  queryParams.categoryId = null
  handleQuery()
}

// 状态样式
const getStatusType = (status) => {
  const types = {
    '待生成': 'info',
    '生成中': 'warning',
    '生成完成': 'success',
    '生成失败': 'danger'
  }
  return types[status] || 'info'
}

// 预览视频
const handlePreview = (row) => {
  previewDialog.videoUrl = row.videoUrl
  previewDialog.visible = true
}

// 下载视频
const handleDownload = (row) => {
  window.open(row.videoUrl)
}

// 重试生成
const handleRetry = async (row) => {
  try {
    await retryTask(row.id)
    ElMessage.success('已重新提交生成任务')
    await getList()
  } catch (error) {
    ElMessage.error(error.message || '重试失败')
  }
}

// 分页方法
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 分类选项
const categoryOptions = ref([])

// 加载分类数据
const loadCategories = async () => {
  try {
    const { data } = await getCategoryTree('')
    categoryOptions.value = data
  } catch (error) {
    ElMessage.error('获取分类失败')
  }
}

// 初始化
onMounted(() => {
  getList()
  loadCategories()
})

// 组件销毁前清理定时器
onBeforeUnmount(() => {
  stopRefreshTimer()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left, .right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.preview-video {
  width: 100%;
  max-height: 450px;
  background: #000;
}

.el-descriptions {
  padding: 20px;
}

:deep(.el-table__expand-icon) {
  margin-right: 8px;
}

.task-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.task-detail {
  padding: 20px;
}

.article-content {
  max-width: 600px;
  white-space: pre-wrap;
  color: #666;
}

.preview-video {
  width: 100%;
  max-height: 450px;
}
</style>